package com.github.binarylei.curator.watcher;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * NodeCache 节点监听
 *
 * @author: leigang
 * @version: 2018-04-06
 */
public class ZkCuratorWatcher1 {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;

    @Test
    public void test() throws Exception {
        //1. 重试策略：初试时间为1s，重试10次
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 10);

        //2. 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SEESION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();

        //3. 开启连接
        cf.start();

        //4. 建立一个cache缓存
        NodeCache cache = new NodeCache(cf, "/curator", false);
        cache.start(true);

        cache.getListenable().addListener(new NodeCacheListener() {
            //触发事件为创建、更新、删除节点
            @Override
            public void nodeChanged() throws Exception {
                ChildData data = cache.getCurrentData();
                if (data != null) {
                    System.out.println("路径为：" + cache.getCurrentData().getPath());
                    System.out.println("数据为：" + new String(cache.getCurrentData().getData()));
                    System.out.println("状态为：" + cache.getCurrentData().getStat());
                } else {
                    System.out.println("删除节点");
                }
                System.out.println("================================================");
            }
        });

        Thread.sleep(1000);
        cf.create().forPath("/curator", "123".getBytes());

        Thread.sleep(1000);
        cf.setData().forPath("/curator", "12344".getBytes());

        Thread.sleep(1000);
        cf.delete().forPath("/curator");
        Thread.sleep(10 * 1000);

        cf.close();
    }
}
